package com.mindskip.xzs.controller.student;

import cn.hutool.core.collection.CollUtil;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.domain.*;
import com.mindskip.xzs.domain.enums.ExamPaperAnswerStatusEnum;
import com.mindskip.xzs.domain.enums.ExamPaperTypeEnum;
import com.mindskip.xzs.domain.question.QuestionObject;
import com.mindskip.xzs.event.CalculateExamPaperAnswerCompleteEvent;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.service.ExamPaperAnswerService;
import com.mindskip.xzs.service.ExamPaperService;
import com.mindskip.xzs.service.SubjectService;
import com.mindskip.xzs.service.TextContentService;
import com.mindskip.xzs.service.VideoService;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.ExamUtil;
import com.mindskip.xzs.utility.HtmlUtil;
import com.mindskip.xzs.utility.JsonUtil;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.admin.exam.ExamPaperEditRequestVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperReadVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperSubmitItemVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperSubmitVM;
import com.mindskip.xzs.viewmodel.student.exampaper.ExamPaperAnswerPageResponseVM;
import com.mindskip.xzs.viewmodel.student.exampaper.ExamPaperAnswerPageVM;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@RestController("StudentExamPaperAnswerController")
@RequestMapping(value = "/api/student/exampaper/answer")
public class ExamPaperAnswerController extends BaseApiController {

    private final ExamPaperAnswerService examPaperAnswerService;
    private final ExamPaperService examPaperService;
    private final SubjectService subjectService;
    private final ApplicationEventPublisher eventPublisher;
    private final VideoService videoService;
    private final TextContentService textContentService;

    @Autowired
    public ExamPaperAnswerController(ExamPaperAnswerService examPaperAnswerService, ExamPaperService examPaperService, SubjectService subjectService, ApplicationEventPublisher eventPublisher,
                                     VideoService videoService, TextContentService textContentService) {
        this.examPaperAnswerService = examPaperAnswerService;
        this.examPaperService = examPaperService;
        this.subjectService = subjectService;
        this.eventPublisher = eventPublisher;
        this.videoService = videoService;
        this.textContentService = textContentService;
    }


    @RequestMapping(value = "/pageList", method = RequestMethod.POST)
    public RestResponse<PageInfo<ExamPaperAnswerPageResponseVM>> pageList(@RequestBody @Valid ExamPaperAnswerPageVM model) {
        model.setCreateUser(getCurrentUser().getId());
        PageInfo<ExamPaperAnswer> pageInfo = examPaperAnswerService.studentPage(model);
        PageInfo<ExamPaperAnswerPageResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> {
            ExamPaperAnswerPageResponseVM vm = modelMapper.map(e, ExamPaperAnswerPageResponseVM.class);
            Subject subject = subjectService.selectById(vm.getSubjectId());
            vm.setDoTime(ExamUtil.secondToVM(e.getDoTime()));
            vm.setSystemScore(ExamUtil.scoreToVM(e.getSystemScore()));
            vm.setUserScore(ExamUtil.scoreToVM(e.getUserScore()));
            vm.setPaperScore(ExamUtil.scoreToVM(e.getPaperScore()));
            vm.setSubjectName(subject.getName());
            vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            if (vm.getPaperName().contains("实操")) {
                Video video = new Video();
                video.setVideoType(1);
                video.setCreateUserId(model.getCreateUser());
                video.setVideoDesc(vm.getPaperName());
                video.setIsCheck(0);
                //video.setVideoPath(null == e.getTaskExamId()? null : String.valueOf(e.getExamPaperId()));
                List<Video> videoList = videoService.getVideoPaper(video);
                String sysTemScore = "已批阅";
                String desc = "通过";
                if (!CollUtil.isEmpty(videoList)) {
                     sysTemScore = "批阅中";
                     desc = "批阅中";
                     vm.setStatus(1);
                     vm.setQuestionCorrect(vm.getQuestionCount() - videoList.size());
                }else {
                    vm.setStatus(2);
                    desc = "通过";
                    video.setIsCheck(1);
                    //查询视频是否通过
                    List<Video> videoList2 = videoService.getVideoPaper(video);
                    Boolean flag = false;
                    int i = 0;
                    if (CollUtil.isNotEmpty(videoList2)) {
                        for (Video video1 : videoList2) {
                            Integer isPass = video1.getIsPass();
                            if (1 == isPass) {
                                i++;
                                flag = true;
                                continue;
                            }
                        }
                    }
                    if (flag) {
                        desc = "不通过";
                        vm.setQuestionCorrect(i);
                    }else {
                        vm.setQuestionCorrect(vm.getQuestionCount());
                    }

                }
                vm.setSystemScore(sysTemScore);
                vm.setUserScore(desc);
                vm.setPaperScore(desc);
                //
            }
            return vm;
        });

        return RestResponse.ok(page);
    }


    @RequestMapping(value = "/answerSubmit", method = RequestMethod.POST)
    public RestResponse answerSubmit(@RequestBody @Valid ExamPaperSubmitVM examPaperSubmitVM) {
        User user = getCurrentUser();
        ExamPaperAnswerInfo examPaperAnswerInfo = examPaperAnswerService.calculateExamPaperAnswer(examPaperSubmitVM, user);
        if (null == examPaperAnswerInfo) {
            return RestResponse.fail(2, "试卷不能重复做");
        }
        ExamPaperAnswer examPaperAnswer = examPaperAnswerInfo.getExamPaperAnswer();
        String paperName = examPaperAnswer.getPaperName();
        Integer taskId = examPaperAnswer.getTaskExamId();
        if (paperName.contains("实操考试")) {
            //需要将数据记录到视频批阅里面去
            List<ExamPaperQuestionCustomerAnswer> answerList = examPaperAnswerInfo.getExamPaperQuestionCustomerAnswers();
            if (CollUtil.isNotEmpty(answerList)) {
                for (ExamPaperQuestionCustomerAnswer answer : answerList) {
                    //获取试卷id
                    Integer paperId = taskId;
                    Integer questionContentId = answer.getQuestionTextContentId();
                    Integer questionId = answer.getQuestionId();
                    //
                    String url = answer.getAnswer();
                    if(StringUtils.isEmpty(url)){
                        return RestResponse.fail(2, "请上传完所有视频提交!");
                    }
                    TextContent textContent = textContentService.selectById(questionContentId);
                    QuestionObject questionObject = JsonUtil.toJsonObject(textContent.getContent(), QuestionObject.class);
                    String clearHtml = HtmlUtil.clear(questionObject.getTitleContent());
                    //根据题目ID找题目名称
                    Video video = new Video();
                    video.setCreateTime(new Date());
                    video.setIsPass(1);
                    video.setVideoUrl(answer.getAnswer());
                    video.setTag(String.valueOf(questionId));
                    video.setVideoType(1);
                    video.setVideoName(clearHtml);
                    video.setVideoDesc(paperName);
                    video.setCreateUserId(user.getId());
                    video.setVideoPath(paperId.toString());
                    video.setIsCheck(0);
                    videoService.insertSelective(video);
                }
            }
        }
        Integer userScore = examPaperAnswer.getUserScore();
        String scoreVm = ExamUtil.scoreToVM(userScore);
        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = user.getUserName() + " 提交试卷：" + examPaperAnswerInfo.getExamPaper().getName()
                + " 得分：" + scoreVm
                + " 耗时：" + ExamUtil.secondToVM(examPaperAnswer.getDoTime());
        if (paperName.contains("实操考试")) {
            content = "请等待后台视频审核批阅";
            scoreVm = "后台视频审核批阅中";
        }else {
            scoreVm = scoreVm + "分";
        }
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new CalculateExamPaperAnswerCompleteEvent(examPaperAnswerInfo));
        eventPublisher.publishEvent(new UserEvent(userEventLog));
        return RestResponse.ok(scoreVm);
    }


    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse edit(@RequestBody @Valid ExamPaperSubmitVM examPaperSubmitVM) {
        boolean notJudge = examPaperSubmitVM.getAnswerItems().stream().anyMatch(i -> i.getDoRight() == null && i.getScore() == null);
        if (notJudge) {
            return RestResponse.fail(2, "有未批改题目");
        }

        ExamPaperAnswer examPaperAnswer = examPaperAnswerService.selectById(examPaperSubmitVM.getId());
        ExamPaperAnswerStatusEnum examPaperAnswerStatusEnum = ExamPaperAnswerStatusEnum.fromCode(examPaperAnswer.getStatus());
        if (examPaperAnswerStatusEnum == ExamPaperAnswerStatusEnum.Complete) {
            return RestResponse.fail(3, "试卷已完成");
        }
        String score = examPaperAnswerService.judge(examPaperSubmitVM);
        User user = getCurrentUser();
        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = user.getUserName() + " 批改试卷：" + examPaperAnswer.getPaperName() + " 得分：" + score;
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new UserEvent(userEventLog));
        return RestResponse.ok(score);
    }

    @RequestMapping(value = "/read/{id}", method = RequestMethod.POST)
    public RestResponse<ExamPaperReadVM> read(@PathVariable Integer id) {
        ExamPaperAnswer examPaperAnswer = examPaperAnswerService.selectById(id);
        ExamPaperReadVM vm = new ExamPaperReadVM();
        ExamPaperEditRequestVM paper = examPaperService.examPaperToVM(examPaperAnswer.getExamPaperId());
        ExamPaperSubmitVM answer = examPaperAnswerService.examPaperAnswerToVM(examPaperAnswer.getId());
        vm.setPaper(paper);
        vm.setAnswer(answer);
        if(examPaperAnswer.getPaperName().contains("实操考试")){
            List<ExamPaperSubmitItemVM> answerItems =  answer.getAnswerItems();
            if(CollUtil.isNotEmpty(answerItems)){
                for(ExamPaperSubmitItemVM examPaperSubmitItemVM : answerItems){
                    //查询questionId 通过状态
                    Integer questionId = examPaperSubmitItemVM.getQuestionId();
                    if(null == questionId){
                        questionId = 0;
                    }
                    Video video = new Video();
                    video.setTag(String.valueOf(questionId));
                    video.setCreateUserId(examPaperAnswer.getCreateUser());
                    Video video1 = videoService.getVideoByTag(video);
                    if(null != video1){
                        //获取是否通过
                        int isCheck = video1.getIsCheck();
                        if(isCheck == 0){
                            examPaperSubmitItemVM.setScore("批阅中");
                        }else {
                            int isPass= video1.getIsPass();
                            if(isPass == 0){
                                examPaperSubmitItemVM.setScore("不通过");
                            }else {
                                examPaperSubmitItemVM.setScore("通过");
                            }
                        }
                    }

                }
            }
        }
        return RestResponse.ok(vm);
    }

    @RequestMapping(value = "/answerSubmit2", method = RequestMethod.POST)
    public RestResponse answerSubmit2(@RequestBody @Valid ExamPaperSubmitVM examPaperSubmitVM) {
        User user = getCurrentUser();
        //判断是否是正式考试
        ExamPaperAnswerInfo examPaperAnswerInfo = examPaperAnswerService.calculateExamPaperAnswer(examPaperSubmitVM, user);
        if (null == examPaperAnswerInfo) {
            return RestResponse.fail(2, "试卷不能重复做");
        }
        ExamPaperAnswer examPaperAnswer = examPaperAnswerInfo.getExamPaperAnswer();
        Integer userScore = examPaperAnswer.getUserScore();
        String scoreVm = ExamUtil.scoreToVM(userScore);
        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = user.getUserName() + " 提交试卷：" + examPaperAnswerInfo.getExamPaper().getName()
                + " 得分：" + scoreVm
                + " 耗时：" + ExamUtil.secondToVM(examPaperAnswer.getDoTime());
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new CalculateExamPaperAnswerCompleteEvent(examPaperAnswerInfo));
        eventPublisher.publishEvent(new UserEvent(userEventLog));
        return RestResponse.ok(scoreVm);
    }


}
